#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <string>
#include <memory>

#include "Log.hpp"
#include "nocopy.hpp"
#include "InetAddr.hpp"

static const uint16_t gport = 8888;
static const int gsockfd = -1;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

class Server
{
public:
    Server(uint16_t port = gport)
        : _localport(port),
          _isrunning(false),
          _socketfd(gsockfd)
    {
    }

    ~Server()
    {
        if (_socketfd != -1)
        {
            ::close(_socketfd);
        }
    }

    void Init()
    {
        // 创建套接字
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(FATAL, "socket creat error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket creat success\n");

        // bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));

        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_family = AF_INET;

        int n = ::bind(_socketfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "socket bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind success\n");
    }

    void Start()
    {
        _isrunning = true;

        while (_isrunning)
        {
            // 接收
            char buff[1024];
            sockaddr_in perr;
            socklen_t len = sizeof(perr);
            int n = recvfrom(_socketfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&perr, &len);
            if (n < 0)
            {
                LOG(FATAL, "server recvfrom error\n");
                exit(1);
            }
            IntAddr in(perr);
            std::cout << "[" << in.Ip() << ":" << in.Port() << "]# " << buff << std::endl;

            // 处理
            buff[n] = 0;
            std::string mess = "[server echo]# ";
            mess += buff;

            // 发送
            n = sendto(_socketfd, mess.c_str(), mess.size(), 0, (struct sockaddr *)&perr, len);
            if (n < 0)
            {
                LOG(FATAL, "server sendto error\n");
                exit(1);
            }
        }
    }

private:
    int _socketfd;
    uint16_t _localport;
    bool _isrunning;
};
